<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\Transfer;
use app\models\user\User;
use app\models\user\UserAccount;

class TransferController extends H5Controller
{
    // 余额转让
    public function actionExecute()
    {

        $transaction = \Yii::$app->db->beginTransaction();

        try {
            $send_id = $this->user->id;
            $received_id = $this->post('received_id');

            // 备注
            $remark = $this->post('remark');

            if ($send_id == $received_id) {
                return $this->fail('错误');
            }

            $amount = intval($this->post('amount'));
            if ($amount <= 0.01) {
                return $this->fail('金额错误');
            }
            $send = UserAccount::findOne(['user_id' => $send_id]);
            $received = UserAccount::findOne(['user_id' => $received_id]);
            // 手机号也行
            if (!$received) {
                $_id = User::find()
                    ->where(['mobile' => trim($received_id)])
                    ->select(['id'])
                    ->scalar();
                if ($_id) {
                    $received_id = $_id;
                    $received = UserAccount::findOne(['user_id' => $_id]);
                }

            }
            if ($received_id == $send_id) {
                return $this->fail('自己不能转给自己!');
            }
            if (!$send || !$received) {
                return $this->fail('操作错误,请检查用户id或者手机号');
            }
            if ($send->balance < $amount) {
                return $this->fail('余额不足');
            }
            $send->balance -= $amount;
            $send->save();
            $received->balance += $amount;
            $received->save();


            // 日志
            $log = new Transfer();
            $log->send_id = $send_id;
            $log->received_id = $received_id;
            $log->amount = $amount;
            $log->remark = $remark;
            $log->save();

            // var_dump($log->getFirstErrors());exit;

            $transaction->commit();

            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // 显示昵称
    public function actionShow()
    {
        $id = $this->post('id');
        $user = User::findOne(['id' => $id]);
        if (!$user) {
            $user = User::find()
                ->where(['mobile' => trim($id)])
                ->one();
        }

        if ($user) {
            $name = '';
            if ($user->nickname) {
                $name = base64_decode($user->nickname);
            }

            return $this->success($name);
        }

        return $this->fail('接收者错误');
    }
}